package Javaa.Base.Thread;

//create an example of synchronous usage in Java
// add callbacks to indicate task completion

public class Synchronous {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new Task("Task 1"));
        Thread thread2 = new Thread(new Task("Task 2"));

        thread1.start();
        try {
            thread1.join(); // Wait for thread1 to finish
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread2.start();
    }
}


public class TicketSystem {
    private int ticket = 1; // 共享资源（1张票）

    // 同步方法：多个线程排队执行
    public synchronized void buyTicket(String threadName) {
        if (ticket > 0) {
            System.out.println(threadName + "抢到票了！");
            ticket--;
        } else {
            System.out.println(threadName + "没抢到票...");
        }
    }

    public static void main(String[] args) {
        TicketSystem system = new TicketSystem();
        // 启动10个线程抢票（同步执行）
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> system.buyTicket(Thread.currentThread().getName())).start();
        }
    }
}